<template>
	<van-tabs :active="selectItem" @click-tab="handleClick">
		<van-tab
			v-for="item in showItems"
			:key="item.value"
			:style="{ color: item.color }"
			:title="item.text"
			:name="item.value"
		></van-tab>
	</van-tabs>
</template>
<script setup lang="ts">
import { ICodeListItem, ICodeListResult, IParam } from '@/core';
import { Ref } from 'vue';
import { quickGroupProps, getDefaultSelect } from './quick-group';
const props = defineProps(quickGroupProps);
const emit = defineEmits<{
	(name: 'valueChange', item: ICodeListItem): void;
}>();
//  数据
const showItems: Ref<ICodeListItem[]> = ref([]);

const selectItem: Ref<string | number> = ref('');
const handleByCodeList = async () => {
	if (!props.codeListTag) {
		console.warn('未配置代码表');
	}
	try {
		const response = await App.getAppCodeListHelper().getCodeListItems(
			props.codeListTag as string,
			props.context,
			props.viewParams
		);
		if (response.ok && response.data.length > 0) {
			const defaultItem = getDefaultSelect(response.data);
			showItems.value.length = 0;
			showItems.value.push(...response.data);
			handleClick(
				defaultItem ? defaultItem : { name: showItems.value[0].value }
			);
		}
	} catch (error) {
		console.log(error);
	}
};

const isSelect = (item: ICodeListItem): boolean => {
	return !!(selectItem.value === item.value);
};

const handleClick = (item: any) => {
	const _selectItem: ICodeListItem | undefined = showItems.value.find(
		(_item: ICodeListItem) => {
			return _item.value === item.name;
		}
	);
	if (!_selectItem || isSelect(_selectItem)) {
		return;
	}
	selectItem.value = _selectItem.value;
	emit('valueChange', _selectItem);
};

const handleByItems = () => {};
const init = () => {
	if (props.type === 'CODELIST') {
		handleByCodeList();
	} else if (props.type === 'ITEMS') {
		handleByItems();
	}
};
init();
</script>
